package com.test.springboot.kaptcha.controller;

import com.baomidou.kaptcha.Kaptcha;
import com.baomidou.kaptcha.exception.KaptchaIncorrectException;
import com.baomidou.kaptcha.exception.KaptchaNotFoundException;
import com.baomidou.kaptcha.exception.KaptchaTimeoutException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/8/12 23:28
 * @package com.test.springboot.kaptcha.controller
 * @description 文件说明
 */
@Slf4j
@RestController
@RequestMapping(value = "/kaptcha")
public class KaptchaController {

    @Autowired
    private Kaptcha kaptcha;

    /**
     * 获取Kaptcha验证码
     */
    @GetMapping("/getCode")
    public void getKaptchaImg() {
        //默认900秒
        String render = kaptcha.render();
        log.info(render);
    }

    /**
     * 验证验证码
     *
     * @param code 验证码
     * @return
     */
    @PostMapping("/validCode")
    public String validCode(@RequestParam(value = "code") String code) {
        try {
            kaptcha.validate(code);
        } catch (Exception e) {
            if (e instanceof KaptchaIncorrectException) {
                return "验证码不正确";
            } else if (e instanceof KaptchaNotFoundException) {
                return "验证码未找到";
            } else if (e instanceof KaptchaTimeoutException) {
                return "验证码过期";
            } else {
                return "验证码渲染失败";
            }
        }
        return "验证通过";
    }

}
